package Demo603;



import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {

    private static DbUntil dbUntil = new DbUntil();
    Connection connection = dbUntil.getCon();

    public UserDao() throws SQLException, ClassNotFoundException {
    }

    public User findUser(String username, String password) throws SQLException {
        // 4. 编写 SQL 语句
        String sql = "select * from users where username = ? and password = ?";

        // 5. 执行 SQL 语句
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        // 5.1 给问号赋值
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, password);

        // 查询是否有结果的 ResultSet，接收查询语句查询出来的结果
        ResultSet resultSet = preparedStatement.executeQuery();
        User user = new User();

        if (resultSet.next()) {
            // 把数据拿出来
            int id = resultSet.getInt("id");
            String name = resultSet.getString("username");
            String pwd = resultSet.getString("password");

            // 交给 User：实际上就是给对象进行赋值：set 构造函数
            user = new User(id, username, password);
            user.setId(id);
            user.setUsername(name);
            user.setPassword(pwd);
        }

        return user;
    }
}




